<template>
  <ModalPanel
    :visible="visible"
    :width="1200"
    :title="t('添加人员')"
    @submit="submit"
    @close="close"
  >
    <template #left>
      <OrganizationalTree @select="handleSelect" />
    </template>
    <!-- 已选 -->
    <Selected
      v-if="visible"
      type="user"
      :list="data.selectedList"
      @abolish="abolishChecked"
      :disabledIds="props.disabledIds"
    />
    <SearchBox @search="search" />
    <div class="list-page-box" v-if="visible && data.list.length > 0">
      <UserCard
        :class="data.selectedIds.includes(item.id) ? 'picked' : 'not-picked'"
        :disabled="props.disabledIds && props.disabledIds.includes(item.id) ? true : false"
        v-for="(item, index) in data.list"
        :key="index"
        :item="item"
        @click="checked(item)"
      >
        <template #check>
          <a-checkbox size="small" :checked="data.selectedIds.includes(item.id)" />
        </template>
      </UserCard>
      <div class="page-box">
        <a-pagination
          v-model:current="data.page.current"
          :pageSize="data.page.pageSize"
          :total="data.page.total"
          show-less-items
      /></div>
    </div>
    <EmptyBox v-if="data.list.length == 0" />
  </ModalPanel>
</template>

<script setup lang="ts">
  import { computed, onMounted, reactive, watch } from 'vue';
  import OrganizationalTree from '/@/components/SelectOrganizational/src/OrganizationalTree.vue';
  import UserCard from '/@/components/SelectOrganizational/src/card/UserCard.vue';
  import Selected from '/@/components/SelectOrganizational/src/Selected.vue';
  import { ModalPanel, EmptyBox, SearchBox } from '/@/components/ModalPanel/index';
  import { getUserList, getUserMulti } from '/@/api/system/user';
  import { UserInfo } from '/@/api/system/user/model';
  import { cloneDeep } from 'lodash-es';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const emits = defineEmits(['change', 'changeNames', 'close']);
  const props = withDefaults(
    defineProps<{
      selectedIds: Array<string>;
      disabledIds?: Array<string>;
      multiple?: Boolean;
      visible: Boolean;
    }>(),
    {
      selectedIds: () => {
        return [];
      },
      disabledIds: () => {
        return [];
      },
    },
  );
  let data: {
    multiSelect: boolean;
    page: { current: number; total: number; pageSize: number };
    list: Array<UserInfo>;
    selectedList: Array<UserInfo>;
    selectedIds: Array<string>;
    searchConfig: {
      keyword: string;
      deptId: string;
    };
  } = reactive({
    multiSelect: false,
    page: {
      current: 1,
      total: 0,
      pageSize: 9,
    },
    selectedIds: [],
    list: [],
    selectedList: [],
    searchConfig: {
      keyword: '',
      deptId: '',
    },
  });

  const paramRef = computed(() => {
    return {
      limit: data.page.current,
      size: data.page.pageSize,
      departmentId: data.searchConfig.deptId,
      keyword: data.searchConfig.keyword,
    };
  });

  watch(
    () => data.page.current,
    () => {
      getList();
    },
  );
  onMounted(() => {
    show();
  });
  async function show() {
    data.selectedIds = [];
    data.selectedList = [];
    data.page.current = 1;
    data.page.total = 0;
    data.searchConfig.deptId = '';
    if (props.selectedIds && Array.isArray(props.selectedIds)) {
      data.selectedIds = cloneDeep(props.selectedIds);
    }
    await getList();
    await getSelectedList();
  }
  function submit() {
    emits('change', data.selectedIds);
    changeSelectedNames();
    close();
  }
  function close() {
    data.list = [];
    data.selectedIds = [];
    data.selectedList = [];
    emits('close', false);
  }
  function checked(item) {
    if (
      props.disabledIds &&
      Array.isArray(props.disabledIds) &&
      props.disabledIds.includes(item.id)
    ) {
      return;
    }
    if (props.multiple && props.multiple == true) {
      if (data.selectedIds.includes(item.id)) {
        data.selectedIds.splice(
          data.selectedIds.findIndex((itemId) => itemId === item.id),
          1,
        );
        data.selectedList.splice(
          data.selectedList.findIndex((ele) => ele.id === item.id),
          1,
        );
      } else {
        data.selectedIds.push(item.id);
        data.selectedList.push(item);
      }
    } else {
      if (data.selectedIds.includes(item.id)) {
        data.selectedIds = [];
        data.selectedList = [];
      } else {
        data.selectedIds = [item.id];
      }
    }
  }

  async function getList() {
    data.list = [];
    data.page.total = 0;
    let res = await getUserList(paramRef.value);
    if (res.total) {
      data.page.total = res.total;
    }
    if (res.list.length > 0) {
      res.list.forEach((ele) => {
        let item = {
          name: ele.name, //姓名
          id: ele.id, //ID
          code: ele.code, //code
          gender: ele.gender ? ele.gender : -1, //性别
        };
        data.list.push(item);
      });
    }
  }
  function search(keyword: string) {
    data.page.current = 1;
    data.searchConfig.keyword = keyword;
    getList();
  }
  function handleSelect(deptId = '') {
    data.page.current = 1;
    data.searchConfig.deptId = deptId;
    getList();
  }
  async function getSelectedList() {
    let users = await getUserMulti(data.selectedIds.join(','));
    if (users.length > 0) {
      users.forEach((ele) => {
        data.selectedList.push({
          name: ele.name, //姓名
          id: ele.id, //ID
          code: ele.code, //code
          gender: ele.gender ? ele.gender : -1, //性别
        });
      });
      changeSelectedNames();
    }
  }
  function changeSelectedNames() {
    let userNames = data.selectedList
      .map((ele) => {
        return ele.name;
      })
      .join(',');
    emits('changeNames', userNames);
  }
  function abolishChecked(id: string) {
    data.selectedList = data.selectedList.filter((ele) => {
      return ele.id != id;
    });
    data.selectedIds.splice(
      data.selectedIds.findIndex((itemId) => itemId === id),
      1,
    );
  }
</script>
